__author__ = 'st316'
'''
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?
do not destroy the list
'''


# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def __repr__(self):
        return self.val.__repr__()


class Solution:
    # @param head, a ListNode
    # @return a list node
    def detectCycle(self, head):
        if not head:
            return None
        p = head
        q = head
        flag = False
        while p.next and q.next and q.next.next:
            p = p.next
            q = q.next.next
            if p == q:
                flag = True
                break
        if flag:
            p = head
            while p != q:
                p = p.next
                q = q.next
            return p
        return None

    # @param head, a ListNode
    # @return a list node
    def detectCycleX(self, head):
        if not head:
            return None
        p = head
        while p:
            if p.next == p:
                return p
            q = p.next
            p.next = p
            p = q
        return None


if __name__ == '__main__':
    s = Solution()
    head = ListNode(3)
    head.next = ListNode(2)
    head.next.next = ListNode(0)
    head.next.next.next = ListNode(-4)
    head.next.next.next.next = head.next
    print s.detectCycle(head)